package com.shensi.adminCollect.service.coupon.impl;

import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.DateUtils;
import com.shensi.adminCollect.domain.coupon.CouponIssueRelation;
import com.shensi.adminCollect.domain.coupon.CouponUser;
import com.shensi.adminCollect.domain.coupon.vo.CouponUserSumVo;
import com.shensi.adminCollect.mapper.coupon.CouponUserMapper;
import com.shensi.adminCollect.service.coupon.ICouponInfoService;
import com.shensi.adminCollect.service.coupon.ICouponIssueRelationService;
import com.shensi.adminCollect.service.coupon.ICouponUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优惠劵Service业务层处理
 * 
 * @author qujia
 * @date 2021-08-09
 */


@Service
public class CouponUserServiceImpl implements ICouponUserService
{
    @Autowired
    private CouponUserMapper  couponUserMapper;
    @Autowired
    private ICouponIssueRelationService couponIssueRelationService;
    @Autowired
    private ICouponInfoService couponInfoService;

    /**
     * 查询人员优惠劵
     * 
     * @param id 人员优惠劵ID
     * @return 人员优惠劵
     */
    @Override
    public CouponUser selectCouponUserById(Integer id)
    {
        return couponUserMapper.selectCouponUserById(id);
    }

    /**
     * 查询人员优惠劵列表
     * 
     * @param couponUser 人员优惠劵
     * @return 人员优惠劵
     */
    @Override
    public List<CouponUser> selectCouponUserList(CouponUser couponUser)
    {
        return couponUserMapper.selectCouponUserList(couponUser);
    }

    @Override
    public CouponUserSumVo selectCouponUserSum(CouponUser couponUser)
    {
        return couponUserMapper.selectCouponUserSum(couponUser);
    }

    @Override
    public void logicDeleteCouponUser(int id) {
        couponUserMapper.logicDeleteCouponUser(id);
    }

    // 批量逻辑删除优惠券用户
    @Override
    public void batchLogicDeleteCouponUser(List<Integer> ids) {
        couponUserMapper.batchLogicDeleteCouponUser(ids);
    }
    /**
     * 新增人员优惠劵
     * 
     * @param couponUser 人员优惠劵
     * @return 结果
     */
    @Override
    public int insertCouponUser(CouponUser  couponUser)
    {
        couponUser.setCreateTime(DateUtils.getNowDate());
        return couponUserMapper.insertCouponUser(couponUser);
    }

    /**
     * 修改人员优惠劵
     * 
     * @param couponUser 人员优惠劵
     * @return 结果
     */
    @Override
    public int updateCouponUser(CouponUser  couponUser)
    {
        return couponUserMapper.updateCouponUser(couponUser);
    }

    /**
     * 批量删除人员优惠劵
     * 
     * @param ids 需要删除的人员优惠劵ID
     * @return 结果
     */
    @Override
    public int deleteCouponUserByIds(String[] ids)
    {
        return couponUserMapper.deleteCouponUserByIds(ids);
    }

    @Override
    public int deleteCouponUserByIds(List<String> ids)
    {
        return couponUserMapper.deleteCouponUserByIdList(ids);
    }

    /**
     * 删除人员优惠劵信息
     * 
     * @param id 人员优惠劵ID
     * @return 结果
     */
    @Override
    public int deleteCouponUserById(Integer id)
    {
        return couponUserMapper.deleteCouponUserById(id);
    }

    @Override
    public List<CouponUser> queryList(CouponUser couponUser) {
        return couponUserMapper.queryList(couponUser);
    }

    @Override
    public int incrCouponUserGiveCount(String mobilePhone, String issueId, int incr) {
        return couponUserMapper.incrCouponUserGiveCount(mobilePhone,issueId,incr);
    }

    @Override
    public void recoveryUserCoupon(String mobilePhone, int activityType, Long bizId, String bizType,boolean failWhenUsed) {
        CouponUser form = new CouponUser();
        form.setMobilePhone(mobilePhone);
        form.setBizId(bizId);
        form.setBizType(bizType);
        form.setActivityType(activityType);
        List<CouponUser> couponUsers = queryList(form);
        if (couponUsers.isEmpty()) {
            return;
        }
        if (failWhenUsed) {
            long count = couponUsers.stream().filter(c -> StringUtils.equals("1", c.getCouponIsUsed())).count();
            if (count>0) {
                throw new CustomException("优惠劵已使用，不能退款");
            }
        }else{
            couponUsers = couponUsers.stream().filter(c -> !StringUtils.equals("1",c.getCouponIsUsed())).collect(Collectors.toList());
        }
        if (couponUsers.isEmpty()) {
            return;
        }
        List<Integer> couponUserIds = couponUsers.stream().map(CouponUser::getId).collect(Collectors.toList());
        HashMap<String, Integer> issueIdMap = new HashMap<>(couponUserIds.size());
        List<String> issueIds = new ArrayList<>(couponUserIds.size());
        for (CouponUser couponUser : couponUsers) {
            String issueId = couponUser.getIssueId();
            Integer c = issueIdMap.get(issueId);
            if (c == null) {
                issueIds.add(issueId);
                issueIdMap.put(issueId, 1);
                continue;
            }
            issueIdMap.put(issueId, c + 1);
        }
        List<CouponIssueRelation> couponIssueRelations = couponIssueRelationService.selectListByIssueIds(issueIds);
        for (CouponIssueRelation relation : couponIssueRelations) {
            Integer con = issueIdMap.get(relation.getIssueId());
            if (con == null) {
                continue;
            }
            couponInfoService.incrGetCouponNum(Math.toIntExact(relation.getCouponId()),con);
        }
        for (Map.Entry<String, Integer> entry : issueIdMap.entrySet()) {
            if (entry.getValue() <= 0) {
                continue;
            }
            incrCouponUserGiveCount(mobilePhone, entry.getKey(), -entry.getValue());
        }
        batchLogicDeleteCouponUser(couponUserIds);
//        deleteCouponUserByIds(couponUserIds);
    }


}
